package workflow

import (
	"fmt"
	"time"
)

// WorkflowState 工作流状态
type WorkflowState string

const (
	StatePending    WorkflowState = "pending"    // 待处理
	StateProcessing WorkflowState = "processing" // 处理中
	StateApproving  WorkflowState = "approving"  // 审批中
	StateResolved   WorkflowState = "resolved"   // 已解决
	StateClosed     WorkflowState = "closed"     // 已关闭
)

// WorkflowStep 工作流步骤
type WorkflowStep struct {
	ID          string        `json:"id"`
	Name        string        `json:"name"`
	Description string        `json:"description"`
	State       WorkflowState `json:"state"`
	Assignee    string        `json:"assignee"`
	Deadline    time.Time     `json:"deadline"`
	CreatedAt   time.Time     `json:"created_at"`
	UpdatedAt   time.Time     `json:"updated_at"`
}

// DisputeWorkflow 争议工作流
type DisputeWorkflow struct {
	ID          string         `json:"id"`
	DisputeID   uint32         `json:"dispute_id"`
	Steps       []WorkflowStep `json:"steps"`
	CurrentStep int            `json:"current_step"`
	Priority    uint32         `json:"priority"`
	State       WorkflowState  `json:"state"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
}

// WorkflowManager 工作流管理器
type WorkflowManager struct {
	workflows map[string]*DisputeWorkflow
}

// NewWorkflowManager 创建工作流管理器
func NewWorkflowManager() *WorkflowManager {
	return &WorkflowManager{
		workflows: make(map[string]*DisputeWorkflow),
	}
}

// CreateDisputeWorkflow 创建争议工作流
func (wm *WorkflowManager) CreateDisputeWorkflow(disputeID uint32, priority uint32) (*DisputeWorkflow, error) {
	workflowID := fmt.Sprintf("WF_%d_%d", disputeID, time.Now().Unix())

	// 根据优先级确定工作流步骤
	steps := wm.getWorkflowSteps(priority)

	workflow := &DisputeWorkflow{
		ID:          workflowID,
		DisputeID:   disputeID,
		Steps:       steps,
		CurrentStep: 0,
		State:       StatePending,
		CreatedAt:   time.Now(),
		UpdatedAt:   time.Now(),
	}

	wm.workflows[workflowID] = workflow
	return workflow, nil
}

// getWorkflowSteps 根据优先级获取工作流步骤
func (wm *WorkflowManager) getWorkflowSteps(priority uint32) []WorkflowStep {
	now := time.Now()

	switch priority {
	case 1: // 低优先级
		return []WorkflowStep{
			{
				ID:          "step1",
				Name:        "客服初审",
				Description: "客服人员初步审核争议",
				State:       StatePending,
				Assignee:    "customer_service",
				Deadline:    now.Add(3 * 24 * time.Hour), // 3天
				CreatedAt:   now,
				UpdatedAt:   now,
			},
			{
				ID:          "step2",
				Name:        "主管审批",
				Description: "主管审批争议解决方案",
				State:       StatePending,
				Assignee:    "supervisor",
				Deadline:    now.Add(7 * 24 * time.Hour), // 7天
				CreatedAt:   now,
				UpdatedAt:   now,
			},
		}
	case 2: // 中优先级
		return []WorkflowStep{
			{
				ID:          "step1",
				Name:        "客服处理",
				Description: "客服人员处理争议",
				State:       StatePending,
				Assignee:    "customer_service",
				Deadline:    now.Add(2 * 24 * time.Hour), // 2天
				CreatedAt:   now,
				UpdatedAt:   now,
			},
			{
				ID:          "step2",
				Name:        "主管审批",
				Description: "主管审批争议解决方案",
				State:       StatePending,
				Assignee:    "supervisor",
				Deadline:    now.Add(4 * 24 * time.Hour), // 4天
				CreatedAt:   now,
				UpdatedAt:   now,
			},
		}
	case 3: // 高优先级
		return []WorkflowStep{
			{
				ID:          "step1",
				Name:        "客服处理",
				Description: "客服人员处理争议",
				State:       StatePending,
				Assignee:    "customer_service",
				Deadline:    now.Add(24 * time.Hour), // 1天
				CreatedAt:   now,
				UpdatedAt:   now,
			},
			{
				ID:          "step2",
				Name:        "主管审批",
				Description: "主管审批争议解决方案",
				State:       StatePending,
				Assignee:    "supervisor",
				Deadline:    now.Add(2 * 24 * time.Hour), // 2天
				CreatedAt:   now,
				UpdatedAt:   now,
			},
			{
				ID:          "step3",
				Name:        "经理审批",
				Description: "经理最终审批",
				State:       StatePending,
				Assignee:    "manager",
				Deadline:    now.Add(3 * 24 * time.Hour), // 3天
				CreatedAt:   now,
				UpdatedAt:   now,
			},
		}
	case 4: // 紧急
		return []WorkflowStep{
			{
				ID:          "step1",
				Name:        "紧急处理",
				Description: "紧急处理争议",
				State:       StatePending,
				Assignee:    "senior_customer_service",
				Deadline:    now.Add(4 * time.Hour), // 4小时
				CreatedAt:   now,
				UpdatedAt:   now,
			},
			{
				ID:          "step2",
				Name:        "经理审批",
				Description: "经理紧急审批",
				State:       StatePending,
				Assignee:    "manager",
				Deadline:    now.Add(8 * time.Hour), // 8小时
				CreatedAt:   now,
				UpdatedAt:   now,
			},
		}
	default:
		return []WorkflowStep{}
	}
}

// ProcessStep 处理工作流步骤
func (wm *WorkflowManager) ProcessStep(workflowID string, stepID string, result string, processedBy string) error {
	workflow, exists := wm.workflows[workflowID]
	if !exists {
		return fmt.Errorf("工作流不存在: %s", workflowID)
	}

	if workflow.CurrentStep >= len(workflow.Steps) {
		return fmt.Errorf("工作流已完成")
	}

	currentStep := &workflow.Steps[workflow.CurrentStep]
	if currentStep.ID != stepID {
		return fmt.Errorf("步骤ID不匹配")
	}

	// 更新当前步骤状态
	currentStep.State = StateProcessing
	currentStep.UpdatedAt = time.Now()

	// 处理步骤
	if err := wm.executeStep(currentStep, result, processedBy); err != nil {
		currentStep.State = StatePending
		return err
	}

	// 移动到下一步
	workflow.CurrentStep++
	workflow.UpdatedAt = time.Now()

	// 检查是否完成
	if workflow.CurrentStep >= len(workflow.Steps) {
		workflow.State = StateResolved
	} else {
		// 激活下一步
		nextStep := &workflow.Steps[workflow.CurrentStep]
		nextStep.State = StatePending
		workflow.State = StateProcessing
	}

	return nil
}

// executeStep 执行工作流步骤
func (wm *WorkflowManager) executeStep(step *WorkflowStep, result string, processedBy string) error {
	// 这里可以根据不同的步骤类型执行不同的逻辑
	switch step.ID {
	case "step1":
		// 客服处理逻辑
		return wm.handleCustomerServiceStep(step, result, processedBy)
	case "step2":
		// 主管审批逻辑
		return wm.handleSupervisorApprovalStep(step, result, processedBy)
	case "step3":
		// 经理审批逻辑
		return wm.handleManagerApprovalStep(step, result, processedBy)
	default:
		return fmt.Errorf("未知的步骤类型: %s", step.ID)
	}
}

// handleCustomerServiceStep 处理客服步骤
func (wm *WorkflowManager) handleCustomerServiceStep(step *WorkflowStep, result string, processedBy string) error {
	// 客服处理逻辑
	step.State = StateProcessing
	step.UpdatedAt = time.Now()

	// 这里可以添加具体的客服处理逻辑
	fmt.Printf("客服处理争议: %s, 处理人: %s, 结果: %s\n", step.Name, processedBy, result)

	return nil
}

// handleSupervisorApprovalStep 处理主管审批步骤
func (wm *WorkflowManager) handleSupervisorApprovalStep(step *WorkflowStep, result string, processedBy string) error {
	// 主管审批逻辑
	step.State = StateApproving
	step.UpdatedAt = time.Now()

	// 这里可以添加具体的主管审批逻辑
	fmt.Printf("主管审批争议: %s, 审批人: %s, 结果: %s\n", step.Name, processedBy, result)

	return nil
}

// handleManagerApprovalStep 处理经理审批步骤
func (wm *WorkflowManager) handleManagerApprovalStep(step *WorkflowStep, result string, processedBy string) error {
	// 经理审批逻辑
	step.State = StateApproving
	step.UpdatedAt = time.Now()

	// 这里可以添加具体的经理审批逻辑
	fmt.Printf("经理审批争议: %s, 审批人: %s, 结果: %s\n", step.Name, processedBy, result)

	return nil
}

// GetWorkflowStatus 获取工作流状态
func (wm *WorkflowManager) GetWorkflowStatus(workflowID string) (*DisputeWorkflow, error) {
	workflow, exists := wm.workflows[workflowID]
	if !exists {
		return nil, fmt.Errorf("工作流不存在: %s", workflowID)
	}

	return workflow, nil
}

// EscalateWorkflow 升级工作流
func (wm *WorkflowManager) EscalateWorkflow(workflowID string, reason string) error {
	workflow, exists := wm.workflows[workflowID]
	if !exists {
		return fmt.Errorf("工作流不存在: %s", workflowID)
	}

	// 添加升级步骤
	escalationStep := WorkflowStep{
		ID:          "escalation",
		Name:        "争议升级",
		Description: fmt.Sprintf("争议升级: %s", reason),
		State:       StatePending,
		Assignee:    "senior_manager",
		Deadline:    time.Now().Add(24 * time.Hour),
		CreatedAt:   time.Now(),
		UpdatedAt:   time.Now(),
	}

	// 插入升级步骤到当前步骤之前
	workflow.Steps = append(workflow.Steps[:workflow.CurrentStep], append([]WorkflowStep{escalationStep}, workflow.Steps[workflow.CurrentStep:]...)...)

	return nil
}
